#!/usr/bin/env bash
# a quick and dirty script to clone all rpm specs from import
# and adopt them for rpm4 from rpm5

UPD_ONLY="${UPD_ONLY:-0}"
RUN_BUILD="${RUN_BUILD:-0}"
# ABF_CLIENT=~/bin/abf-console-client/abf.py
ABF_CLIENT="${ABF_CLIENT:-abf}"
dir0="$PWD"
export dir0

if [ -z "$REPO_DIR" ]; then
	echo 'Define $REPO_DIR!'
	exit 1
fi

if [ ! -f "${dir0}/rpm5-to-rpm4.sh" ]; then
	echo "Script rpm5-to-rpm4.sh not found!"
	exit 1
fi

set -xeu

git config --global core.excludesFile "${HOME}/.gitignore"
if ! grep -q '^.nixtux_changed$' "${HOME}/.gitignore" ; then
	echo .nixtux_changed >> "${HOME}/.gitignore"
fi

# https://nixtux.ru/983
LIST="${LIST:-$(wget -qO- https://abf.rosalinux.ru/api/v1/platforms/4084/projects | sort -u | tac)}"

pushd "$REPO_DIR"

while read -r line
do
	EXISTS=0
	# import/xxx -> xxx
	line_end="$(echo "$line" | awk -F '/' '{print $NF}')"
	if [ -z "$line_end" ]; then
		echo "FAILED: line_end: $line"
		continue
	fi
	if [ -d "$line_end" ]; then
		# assume that, if directory exists, it is a _valid_ git tree
		EXISTS=1
	fi
	case "$EXISTS" in
		1 )
			pushd "$line_end"
			if ! git fetch --all ; then
				echo "FAILED: git fetch: $line"
				continue
			fi
			git reset --hard
			git checkout rosa2019.1
			if ! git reset origin/rosa2019.1 --hard ; then
				echo "FAILED: git reset: $line"
				continue
			fi
			popd
		;;
		0 )
			if ! git clone git@abf.io:${line}.git -b rosa2019.1 ; then
				echo "FAILED: git clone: $line"
				continue
			fi
		;;
	esac
	if [ "$UPD_ONLY" = 1 ]; then continue; fi
	for i in $(ls ${line_end}/*.spec)
	do
		if ! MODE=rpm "$SHELL" "${dir0}/rpm5-to-rpm4.sh" "$i" ; then
			echo "FAILED: rpm mode: $line $i"
			continue
		fi
	done
	if [ -f "${line_end}/.abf.yml" ]; then
		if ! MODE=yaml "$SHELL" "${dir0}/rpm5-to-rpm4.sh" "${line_end}/.abf.yml"; then
			echo "FAILED: yaml mode: $line"
			continue
		fi
	fi
	if [ -f "${line_end}/.nixtux_changed" ]; then
		if [ "$RUN_BUILD" = 1 ]; then
			# --no-extra-tests because release is not bumped
			"$ABF_CLIENT" build --no-extra-tests -b rosa2019.1 -p "$line"
		fi
		rm -f "${line_end}/.nixtux_changed"
	fi
done < <(echo "$LIST")

popd
